<?php


namespace app\backend\controller\v1;

use app\backend\validate\TopicValidate;
use app\common\model\Topic as TopicModel;
use think\exception\ValidateException;
use think\facade\Filesystem;

class Topic extends BaseController
{
    /**
     * 题型列表
     *
     * @return \think\Response
     */
    public function index()
    {
        // 题型表
        $model = new TopicModel();
        // 分页、排序等
        $list = $model
            ->order('id','asc')
            ->field('*')
            ->paginate(10);
        foreach ($list as &$value){
            $value['paper_id']=$value->paper->title;
            $value['subject_id']=$value->subject->title;
            unset($value->degree);
        }
        $page = $list->render();
        //获取列表
        return sucessMsg(200, '获取成功！', ['list' => $list, 'total' => count($list),'page'=>$page]);
    }

    /**
     * 显示创建轮播表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $user = new TopicModel();
        $data = input();
        try {
            validate(TopicValidate::class)->scene('create')->check($data);
            if ($user->save($data)) {
                return sucessMsg(200, '创建成功！');
            }
            return errMsg(500, '创建失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }


    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(400, '请选择数据！');
        }
        $user = TopicModel::find($id);
        $data = input();
        $img = $file = request()->file('image');
        try {
            validate(TopicValidate::class)->scene('update')->check($data);
            if (!empty($img)) {
                $saveName = Filesystem::disk('public')->putFile('/uploads', $file);
                $data['image'] = $saveName;
            }
            if (TopicModel::update($data, ['id'=>$id])) {
                return sucessMsg(200, '修改成功！');
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(400, '请选择要删除的数据');
        }
        if (TopicModel::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(500, '删除失败！');
    }
}